package com.sc.sysconfig.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * 密码加密
 *
 * @author 徐赫阳
 * @date 2021/09/03
 */
public class ShaPWD {
    /**
     * 得到sha256
     *
     * @param pwd 密码
     * @return {@link String}
     */
    public static String getSHA256(String pwd){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(pwd.getBytes(StandardCharsets.UTF_8));
            encodeStr = byte2Hex(messageDigest.digest());
        }catch (Exception e){
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * byte2十六进制
     *
     * @param bytes 字节
     * @return {@link String}
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for(int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if(temp.length() == 1){
                stringBuffer.append(0);
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}
